package com.wzx.mvc.core;

import com.wzx.mvc.annocation.Controller;
import com.wzx.mvc.annocation.RequestMapping;
import com.wzx.mvc.utils.ClassUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DispatcherServlet extends HttpServlet {

    Map<String, Object> singletonObjects = new HashMap<>();
    List<HandlerMethod> handlerMappingList = new ArrayList<>();
    List<HandlerInterceptor> interceptorList = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String scanPackage = config.getInitParameter("scanPackage");
        try {
            this.initHandlerMapping(scanPackage);

            this.initInterceptors(scanPackage);

        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    private void initInterceptors(String scanPackage) throws URISyntaxException, IllegalAccessException, InstantiationException {
        List<Class> allClass = ClassUtil.getAllClass(scanPackage);

        for (Class cls : allClass) {
            if (HandlerInterceptor.class.isAssignableFrom(cls) && !HandlerInterceptor.class.equals(cls)) {
                interceptorList.add((HandlerInterceptor) cls.newInstance());
           }
        }
    }

    private void initHandlerMapping(String scanPackage) throws URISyntaxException, IllegalAccessException, InstantiationException {
        List<Class> allClass = ClassUtil.getAllClass(scanPackage);
        for (Class cls : allClass) {
            if (cls.isAnnotationPresent(Controller.class)) {
                Object controllerOrigin = cls.newInstance();
                singletonObjects.put(ClassUtil.firstWordLower(cls.getSimpleName()), controllerOrigin);

                Controller controller = (Controller) cls.getAnnotation(Controller.class);
                RequestMapping controllerRequestMapping = (RequestMapping) cls.getAnnotation(RequestMapping.class);
                for (Method method : cls.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
                        HandlerMethod hm = new HandlerMethod();
                        hm.setUrl(controllerRequestMapping.value() + methodRequestMapping.value());
                        hm.setMethod(method);
                        hm.setControllerOrigin(controllerOrigin);
                        handlerMappingList.add(hm);
                    }
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.processed(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processed(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setCharacterEncoding("utf-8");
        for (HandlerMethod handlerMethod : handlerMappingList) {
            if (handlerMethod.getUrl().equals(req.getServletPath())) {
                boolean allow = true;

                for (HandlerInterceptor handlerInterceptor : interceptorList) {
                    boolean result = handlerInterceptor.preHandle(req, resp, handlerMethod);
                    if (allow) {
                        allow = result;
                    }
                }

                if (allow) {
                    Object[] params = ParameterResolver.resolver(handlerMethod, req, resp);
                    String result = (String) handlerMethod.getMethod().invoke(handlerMethod.getControllerOrigin(), params);
                    resp.getWriter().println(result);
                    return;
                }
            }
        }
        resp.setStatus(404);
    }
}

